package com.wenan.ui.controls.charts.expand
{
	import com.amcharts.chartClasses.AmGraph;
	import com.amcharts.chartClasses.AmRectangularChart;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.containers.HBox;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.controls.Label;
	import mx.events.FlexEvent;

	public class AmLegendItemRenderer extends HBox
	{
		private var imageState:int = 0;
		private var sortButton:Button;
		public function AmLegendItemRenderer()
		{
			super();
			setStyle("horizontalAlign", "right");
			horizontalScrollPolicy = "off";
			addEventListener(FlexEvent.CREATION_COMPLETE, creationHandler);
		}
		
		public override function set data(value:Object):void
		{
			var _label:Label;
			var graphs:Array = (value as AmSerialChartExpand).graphs;
			var hBox:HBox;
			var image1:HBox;
			var amlegend:AmLegendSpecial;
			for each (var amGraph:AmGraph in graphs)
			{
				hBox = new HBox();
				hBox.name = "contain";
				hBox.setStyle("verticalAlign", "middle");
				image1 = new HBox();
				image1.width = 16;
				image1.height = 16;
				var s2:uint = amGraph.getStyle("color") as uint;
				image1.setStyle("backgroundColor", s2);
				
				_label = new Label();
				_label.id = "legendName";
				_label.text = amGraph.title;
				_label.data = amGraph.valueField;
				
				sortButton = new Button();
				sortButton.styleName = "UpButton";
				sortButton.addEventListener(MouseEvent.CLICK, sortButtonClickHandler);
				
				hBox.addChild(image1);
				hBox.addChild(_label);
//				hBox.addChild(sortButton);
				this.addChild(hBox);
			}
		}
		
		public function sortButtonClickHandler(event:MouseEvent):void
		{
			var s:Label = ((event.target as Button).owner as HBox).getChildAt(1) as Label;
			if (imageState == 0)
			{
				imageState = 1;
				(event.target as Button).styleName = "DownButton";
				this.owner.dispatchEvent(new AmLegendEvent(AmLegendEvent.AMLEGENDASC, s.data.toString()));
			} else 
			{
				imageState = 0;
				(event.target as Button).styleName = "UpButton";
				this.owner.dispatchEvent(new AmLegendEvent(AmLegendEvent.AMLEGENDDESC, s.data.toString()));
			}
		}
		
		private function creationHandler(event:FlexEvent):void
		{
			var als:AmLegendSpecial = this.owner as AmLegendSpecial;
			if (maxHorizontalScrollPosition > 0 && als.count == 1)
			{
				als.dispatchEvent(new Event("showScroll"));
				als.addEventListener("leftScroll", leftScrollHandler);
				als.addEventListener("rightScroll", rightScrollHandler);
			}
			als.count ++;
		}
		
		private function rightScrollHandler(event:Event):void
		{
			this.horizontalScrollPosition += 32;  
		}
		private function leftScrollHandler(event:Event):void
		{
			this.horizontalScrollPosition -= 32;  
		}
	}
}